<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary">
            <router-link class="text-white" :to="{name: '通知公告'}">返回</router-link>
          </a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="学员" prop="student">
            <el-cascader v-model="list" :options="options" :props="props" collapse-tags clearable></el-cascader>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="ruleForm.title" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="正文" prop="text">
            <div class="content" ref="editor" style="text-align:left; width: 375px;"></div>
          </el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">发送</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { uniq } from "underscore";
import uuid from "uuid/v4";
import OSS from "ali-oss";
import E from "wangeditor";
import emoji from "../../../../plugins/emoji.json";
import {
  asynccreatschoolannouncementpush,
  ossupload
} from "../../../../plugins/api.js";
export default {
  name: "sendingannouncement",
  data() {
    return {
      props: { multiple: true },
      list: [],
      ruleForm: {
        ID: null,
        title: "",
        schoolclazzs: "",
        student: [],
        text: ""
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        text: [{ required: true, message: "请添加内容", trigger: "blur" }],
        student: [{ required: true, message: "请添加学生", trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["getschoolstudent", "getschoolclazz"]),
    options() {
      const { getschoolstudent, getschoolclazz } = this;
      const x = [];
      const data = getschoolclazz
        .filter(v => ["2", "3", "4"].includes(v.type))
        .map(v => {
          const student = v.schoolstudentschoolclazz
            .filter(vo => vo.type == "在读")
            .map(vo => vo.schoolstudentid);
          const children = getschoolstudent
            .filter(vo => student.includes(vo.ID))
            .map(vo => {
              x.push(vo.ID);
              return {
                label: vo.name,
                value: vo.ID
              };
            });
          return {
            label: v.name,
            value: v.ID,
            children
          };
        });
      const data2 = getschoolstudent
        .filter(v => !x.includes(v.ID))
        .map(v => {
          return {
            label: v.name,
            value: v.ID
          };
        });
      data.push({
        value: 0,
        label: "没有班级",
        children: data2
      });
      return data;
    }
  },
  mounted() {
    this.editor = new E(this.$refs.editor);
    this.editor.customConfig.zIndex = 100;
    this.editor.customConfig.customUploadImg = this.updateoss;
    this.editor.customConfig.uploadImgMaxLength = 1;
    this.editor.customConfig.emotions = [
      {
        title: "默认",
        type: "image",
        content: emoji
      }
    ];
    this.editor.customConfig.menus = [
      "head",
      "underline",
      "list",
      "justify",
      "quote",
      "emoticon",
      "image",
      "undo"
    ];
    this.editor.create();
  },
  methods: {
    async updateoss(files, insert) {
      const res = await ossupload();
      const client = new OSS({
        region: "oss-cn-qingdao",
        accessKeyId: res.accessKeyId,
        accessKeySecret: res.accessKeySecret,
        stsToken: res.securityToken,
        bucket: "cdn-hterobot"
      });
      const x = files[0].name.split(".");
      const name = x[x.length - 1];
      const url = `school/${uuid()}.${name}`;
      await client.put(url, files[0]);
      insert(`https://cdn.hterobot.com/${url}`);
    },
    async submitForm() {
      let student = [];
      const schoolclazz = [];
      let schoolclazzs = "";
      for (let v of this.list) {
        student.push(v[1]);
        if (v[0]) {
          schoolclazz.push(v[0]);
        }
      }
      student = uniq(student);
      schoolclazzs = uniq(schoolclazz).join(",");
      this.ruleForm.student = student;
      this.ruleForm.schoolclazzs = schoolclazzs;
      this.ruleForm.starttime = new Date();
      this.ruleForm.text = this.editor.txt.html();
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          try {
            await asynccreatschoolannouncementpush(this.ruleForm);
            await this.$store.dispatch("actionschoolannouncementpush");
            this.setaddress = false;
            this.$message.success(`添加成功`);
            this.$router.push({
              name: "通知公告"
            });
          } catch (err) {
            this.$message.error(`添加失败:${err}`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
</style>